﻿using System.Collections;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using System.Xml.Linq;
using iTextSharp.text;

namespace PocoReport
{
    public class Chart:System.Windows.Forms.DataVisualization.Charting.Chart, IPart
    {
        public Style Style { get; protected set; }
        public new string DataSource { get; set; }
        public string Value { get; set; }
        
        public Chart()
        {
            Style = new Style();
        }

        public void Load(XNode node)
        {
            XElement element = (XElement) node;
            Style = new Style(element);

            string s = element.ToString();
            XElement xElement = XElement.Parse(s);
            XAttribute dataSourceAttrib = xElement.Attribute("DataSource");
            if (dataSourceAttrib != null) dataSourceAttrib.Remove();
            XAttribute valueAttrib = xElement.Attribute("Value");
            if (valueAttrib != null) valueAttrib.Remove();
            Serializer.Load(xElement.CreateReader());

            DataSource = element.GetAttribValue("DataSource", null);
            Value = element.GetAttribValue("Value", null);
        }

        public XNode Save()
        {
            StringWriter writer = new StringWriter();
            Serializer.Save(writer);
            XElement element = XElement.Parse(writer.ToString());
            element.SetAttribValue("DataSource", DataSource);
            element.SetAttribValue("Value", Value);
            element.SetAttribValue("Style", Style);
            return element;
        }

        public IElement GetPdfElement(Document document, Style parentStyle, Scope scope)
        {
            foreach (Series series in Series)
            {
                if(!string.IsNullOrEmpty(series.YValueMembers))
                {
                    series.Points.Clear();
                    IEnumerable dataSourceValue = (IEnumerable)scope.GetValue(DataSource);
                    if (dataSourceValue != null)
                    {
                        Scope innerScope = new Scope(scope);
                        foreach (object value in dataSourceValue)
                        {
                            innerScope.Set(Value, value);
                            object yValue = innerScope.GetValue(series.YValueMembers);
                            series.Points.AddY(yValue);
                        }
                    }
                }
            }

            MemoryStream stream = new MemoryStream();
            SaveImage(stream, ChartImageFormat.Png);
            stream.Position = 0;
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(stream);
            Style mergedStyle = Style.Merge(parentStyle, Style);
            Image.SetProperties(image, mergedStyle.Properties);
            return new Chunk(image, 0, 0, true);
        }        
    }
}
